package studykana.activity;

import java.util.ArrayList;
import java.util.Random;

import studykana.adapters.TimHinhAdapter;
import studykana.database.AppData;
import studykana.models.Alphabet;
import toan.da.com.vn.R;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class TimHinhActivity extends Activity {

	private static final String KEY_PREFERENCE_CHECK_HELP = "check_help_again";

	private TimHinhAdapter adapter;
	private ArrayList<Alphabet> listAlphabet;
	private ArrayList<Alphabet> mListAlphabet;
	private ArrayList<Boolean> listIsFirstImage;

	private GridView gvTimHinh;
	private ProgressBar progressBarTime;
	private ImageView imagePause;
	private ImageButton btnSupport;

	CountDownTimer mCountDownTimer;

	private Activity activity = this;
	private int countClick = 0;
	private int position1;
	private int position2;
	private int idOfImage1;
	private View view1;
	private View view2;

	private static final Random r = new Random();
	private Thread thread;

	private long totalMinute = 3 * 1000 * 60;

	private long remainMilli;
	private MyTimer mTimer;
	private AlertDialog.Builder mDialog;
	private MyCustomAlertDialog a;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tim_hinh_activity);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		gvTimHinh = (GridView) findViewById(R.id.gvTimHinh);
		progressBarTime = (ProgressBar) findViewById(R.id.progressBarTime);
		imagePause = (ImageView) findViewById(R.id.imagePause);
		btnSupport = (ImageButton) findViewById(R.id.btnHelpGame);

		mTimer = new MyTimer(totalMinute, 1000);
		mDialog = new MyCustomAlertDialog(activity, getLayoutInflater());
		a = new MyCustomAlertDialog(activity, getLayoutInflater());
		
		loadPreferences();

		prepareGridview();

		imagePause.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mTimer.cancel();
				mTimer = null;
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				builder.setCancelable(false);
				builder.setTitle("Tạm dừng")
						.setPositiveButton("Chơi tiếp",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int item) {
										mTimer = new MyTimer(remainMilli, 1000);
										mTimer.start();
									}
								})
						.setNegativeButton("Chơi lại từ đầu",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										mTimer = new MyTimer(totalMinute, 1000);
										mTimer.start();
										prepareGridview();
										progressBarTime.setProgress(0);
									}
								});
				builder.show();
			}
		});
		gvTimHinh.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				boolean isImageFirst = listIsFirstImage.get(position);
				if (isImageFirst) {
					++countClick;
					if (countClick == 1) {
						// If the first click, open card and save position,
						// view, id of card.
						openCard(view, position);
						position1 = position;
						idOfImage1 = (int) adapter.getItemId(position);
						view1 = view;
					} else if (countClick == 2) {
						// IF the second click, open card.
						openCard(view, position);
						// Save view of card2.
						view2 = view;
						// And compare with first card.
						if (idOfImage1 != adapter.getItemId(position)) {
							// If card1 difference card2, save position.
							position2 = position;
							// Waiting 2.5 minute to close 2 cards.
							thread = new Thread() {
								public void run() {
									try {
										Thread.sleep(2500);
										activity.runOnUiThread(new Runnable() {

											@Override
											public void run() {
												// Close card1.
												closeCard(view1, position1);
											}
										});
										activity.runOnUiThread(new Runnable() {

											@Override
											public void run() {
												// Close card2.
												closeCard(view2, position2);
											}
										});
										// Reset countClick.
										countClick = 0;

									} catch (InterruptedException e) {
										e.printStackTrace();
									}
								};
							};
							thread.start();
						} else {
							// If card2 same card1, don't close they and reset
							// countClick.
							countClick = 0;
							adapter.setColorItem(view1, Color.RED);
							adapter.setColorItem(view2, Color.RED);
						}
					} else if (countClick == 3) {
						// If user click the third card while 2 cards don't
						// close yet
						// then stop thread and close 2 card now.
						thread.interrupt();
						closeCard(view1, position1);
						closeCard(view2, position2);

						// Set countClick = 1 and open current card.
						countClick = 1;
						openCard(view, position);
						position1 = position;
						idOfImage1 = (int) adapter.getItemId(position);
						view1 = view;
					}
				}
			}
		});

		btnSupport.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Show dialog message Guild game.
//				mDialog.setNegativeButton("Đóng",
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								mTimer = new MyTimer(remainMilli, 1000);
//								mTimer.start();
//							}
//						});
//				mDialog.show();
				a.setNegativeButton("Đóng", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mTimer = new MyTimer(remainMilli, 1000);
						mTimer.start();
					}
				});
				a.show();
			}
		});
	}

	private void openCard(View view, int position) {
		adapter.flipCard(view, true);
		listIsFirstImage.set(position, false);
	}

	private void closeCard(View view, int position) {
		adapter.flipCard(view, false);
		listIsFirstImage.set(position, true);
	}

	private void prepareGridview() {
		listAlphabet = (ArrayList<Alphabet>) AppData.listAllAlphabet;
		Alphabet alphabet;
		Alphabet temp;
		mListAlphabet = new ArrayList<Alphabet>();
		int position;
		ArrayList<Alphabet> tempList = new ArrayList<Alphabet>();
		listIsFirstImage = new ArrayList<Boolean>();
		for (int i = 0; i < 8; i++) {
			position = r.nextInt(listAlphabet.size());
			alphabet = new Alphabet(listAlphabet.get(position));
			listAlphabet.remove(position);
			alphabet.setDisplayText(0);
			tempList.add(alphabet);
			temp = new Alphabet(alphabet);
			temp.setDisplayText(1);
			tempList.add(temp);
			listIsFirstImage.add(true);
			listIsFirstImage.add(true);
		}
		mListAlphabet = randomPosOfElement(tempList);
		adapter = new TimHinhAdapter(activity, mListAlphabet);
		gvTimHinh.setAdapter(adapter);
	}

	// random position of elements in array list.
	private ArrayList<Alphabet> randomPosOfElement(ArrayList<Alphabet> arrayList) {
		Alphabet temp;
		ArrayList<Alphabet> resultList = new ArrayList<Alphabet>();
		int position;
		while (arrayList.size() > 0) {
			position = r.nextInt(arrayList.size());
			temp = new Alphabet(arrayList.get(position));
			resultList.add(temp);
			arrayList.remove(position);
		}
		return resultList;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// back to home
		case android.R.id.home:
			mTimer.cancel();
			mTimer = null;
			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			builder.setTitle("Thoát game?")
					.setPositiveButton("Chơi tiếp",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int item) {
									mTimer = new MyTimer(remainMilli, 1000);
									mTimer.start();
								}
							})
					.setNegativeButton("Thoát",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intentHome = new Intent(activity,
											MainActivity.class);
									startActivity(intentHome);
									finish();
								}
							});
			builder.show();

			break;
		default:
			break;
		}
		return true;
	}

	class MyTimer extends CountDownTimer {

		public MyTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);

		}

		@Override
		public void onFinish() {
			// reset all variables
			progressBarTime.setProgress(0);
			remainMilli = 0;
			// Show dialog message stop game.
			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			builder.setTitle("Kết thúc")
					.setMessage("Đã hết thời gian. Bạn có muốn chơi lại?")
					.setPositiveButton("Thoát",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int item) {
									Intent intentHome = new Intent(activity,
											MainActivity.class);
									startActivity(intentHome);
									finish();
								}
							})
					.setNegativeButton("Chơi lại",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									prepareGridview();
									mTimer = new MyTimer(totalMinute, 1000);
									mTimer.start();
								}
							});
			builder.show();
		}

		@Override
		public void onTick(long millisUntilFinished) {

			remainMilli = millisUntilFinished;
			int progerss = (int) (millisUntilFinished / (double) totalMinute * 100);
			progressBarTime.setProgress(progerss);
		}

	}

	private void savePreferences(String key, boolean value) {
		SharedPreferences sharePreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		Editor editor = sharePreferences.edit();
		editor.putBoolean(key, value);
		editor.commit();
	}

	private void loadPreferences() {
		SharedPreferences sharePreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean check = sharePreferences.getBoolean(KEY_PREFERENCE_CHECK_HELP,
				false);
		if (!check) {
			// Show dialog message start game.
			
//			final Dialog dialog = new Dialog(this);
//			dialog.setTitle("Giới thiệu");
//			dialog.setContentView(R.layout.huong_dan_choi_dialog);
//			// Button dialogButtonClose = (Button) dialog
//			// .findViewById(R.id.btnClose);
//			final CheckBox dialogCheckBox = (CheckBox) dialog
//					.findViewById(R.id.cboxAgain);
//			dialogCheckBox.setVisibility(CheckBox.VISIBLE);
//			// dialogButtonClose.setOnClickListener(new OnClickListener() {
//			//
//			// @Override
//			// public void onClick(View v) {
//			// savePreferences(KEY_PREFERENCE_CHECK_HELP,
//			// dialogCheckBox.isChecked());
//			// dialog.dismiss();
//			// mTimer.start();
//			// }
//			// });
//			dialog.show();
		} else {
			mTimer.start();
		}
	}

	private static class MyCustomAlertDialog extends AlertDialog.Builder {
		private View contentDialog;

		protected MyCustomAlertDialog(Context context, LayoutInflater inflater) {
			super(context);
			contentDialog = inflater.inflate(R.layout.huong_dan_choi_dialog, null);
			setCancelable(false);
			setTitle("Hướng dẫn chơi game");
			setIcon(R.drawable.help_icon2);
			setView(contentDialog);
		}

		public View getContentDialog() {
			return contentDialog;
		}
	}
}
